package com.demo.security.entity;

import com.demo.modules.user.po.UsersPO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.*;

@Slf4j
@Data
public class UserDetail extends UsersPO implements Serializable, UserDetails {
    private Long id;
    private String account;
    private String name;
    private String password;
    private String email;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        log.info(this.getRoles());
        log.info("size:",this.getRoleList().size());

        return roleList.stream()
                .filter(Objects::nonNull)  // 过滤空角色对象
                .flatMap(role -> {
                    // 组合三种权限类型
                    List<String> authStrings = new ArrayList<>();

                    // 1. 处理角色码（自动补全ROLE_前缀）
                    if (StringUtils.hasText(role.getCode())) {
                        String roleCode = role.getCode().startsWith("ROLE_") ?
                                role.getCode() : "ROLE_" + role.getCode();
                        authStrings.add(roleCode);
                    }

                    // 2. 解析权限字符串（支持逗号/分号分隔）
                    if (StringUtils.hasText(role.getPermissions())) {
                        Arrays.stream(role.getPermissions().split("[,;]"))
                                .map(String::trim)
                                .filter(perm -> !perm.isBlank())
                                .forEach(authStrings::add);
                    }

                    return authStrings.stream();
                })
                .distinct()  // 去重
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toUnmodifiableList());

    }

    @Override
    public String getUsername() {
        return name;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;//表示账号没有过期
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;//表示账号没有被锁定
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;//表示密码没有过期
    }

    @Override
    public boolean isEnabled() {
        return true;//表示账号可用
    }
}
